import request from '@/utils/request'
import type { Article, ArticleQuery, ArticleListResponse, Result, ArticleStatistics } from '@/api/types'

// 分页查询文章
export function getArticleList(params: ArticleQuery) {
  return request.get<ArticleListResponse>('/api/articles', { params })
}

// 获取文章详情
export function getArticleDetail(id: number) {
  return request.get<Result<Article>>(`/api/articles/${id}`)
    .then(response => {
      if (!response.data?.data) {
        throw new Error('文章不存在')
      }
      return response.data.data
    })
}

// 获取所有分类
export function getAllCategories() {
  return request.get<string[]>('/api/articles/categories')
}

// 获取所有标签
export function getAllTags() {
  return request.get<string[]>('/api/articles/tags')
}

// 获取热门文章
export function getHotArticles(limit: number = 10) {
  return request.get<Article[]>('/api/articles/hot', { params: { limit } })
}

// 获取统计信息
export function getStatistics() {
  return request.get<ArticleStatistics>('/api/articles/statistics')
}

// 触发爬虫
export function triggerCrawl(url: string) {
  return request.post<string>('/api/articles/crawl', null, { params: { url } })
}

// 创建文章
export function createArticleApi(data: Partial<Article>) {
  return request.post<Article>('/api/articles', data)
}

// 更新文章
export function updateArticleApi(data: Partial<Article>) {
  return request.put<Article>(`/api/articles/${data.id}`, data)
}

// 删除文章
export function deleteArticleApi(id: number) {
  return request.delete<void>(`/api/articles/${id}`)
} 